package task

import (
	"database/sql"
	"errors"
	"fmt"

	_ "github.com/denisenkom/go-mssqldb"
)

const (
	DBNET = "tcp"

	DATABASE = ""
)

type Config struct {
	Dbuser   string `json:"dbuser"`
	Dbpass   string `json:"dbpass"`
	Dbport   string `json:"dbport"`
	Category string `json:"category"`
	Version  string `json:"version"`
	Dbserver string `json:"dbserver"`
}

/***
statement:获取数据库句柄
***/

func (conf *Config) Getdb() (DB *sql.DB, err error) {
	var dsn string
	if conf.Category == "mysql" {
		dsn = fmt.Sprintf("%s:%s@%s(%s:%s)/%s", conf.Dbuser, conf.Dbpass, DBNET, conf.Dbserver, conf.Dbport, DATABASE)
	} else if conf.Category == "mssql" {
		dsn = fmt.Sprintf("server=%s;user id=%s;password=%s", conf.Dbserver, conf.Dbuser, conf.Dbpass)
	} else {
		return nil, errors.New("数据库类别未确定，请先选择数据库类别")
	}

	fmt.Println(dsn)
	DB, err = sql.Open(conf.Category, dsn)
	if err != nil {
		return nil, err
	}
	//登陆数据库
	if err := DB.Ping(); err != nil {
		return nil, err
	} else {
		fmt.Println("数据库登录成功！")
		return DB, nil
	}
}

/***
statement: 连接是否正常
***/
func (conf *Config) IsConnect() (bool, error) {
	DB, err := conf.Getdb()
	if err != nil {
		return false, err
	}

	if err := DB.Ping(); err != nil {
		return false, err
	} else {
		return true, nil
	}
}

/***
statement: 获取数据库列表
***/

func (conf *Config) GetDbList() ([]string, error) {
	var databaselist []string
	var querystr string
	//获取数据库句柄
	DB, err := conf.Getdb()
	if err != nil {
		return databaselist, err
	}

	if conf.Category == "mysql" {
		querystr = "show databases"
	} else if conf.Category == "mssql" {
		querystr = `SELECT Name FROM [SysDatabases]`
	}
	rows, err := DB.Query(querystr)

	if err != nil {
		return databaselist, err
	}
	var database string
	for rows.Next() {
		rows.Scan(&database)
		databaselist = append(databaselist, database)

	}

	return databaselist, nil
}
